<template>
    <div class="feature-extr">
        <div class="feature-extr__wrap">
            <!-- 左侧简要案情，要素信息 -->
            <div class="feature-extr__current">
                <div class="feature-extr__current-info">
                    <!-- 简要案情 -->
                    <div class="feature-extr__briefly">
                        <h3 class="main-title">
                            简要案情
                            <el-alert
                                class="ysxx-alert"
                                title="鼠标选中信息后右键进行要素新增或修改"
                                type="info"
                                show-icon
                                :closable="false"
                            >
                            </el-alert>
                        </h3>
                        <textarea-copy :yslxMap="tagTypeMap" @getValue="getValue" :content="ysContentInfo" />
                    </div>
                    <!-- 要素信息 -->
                    <div class="feature-extr__crux">
                        <h3 class="main-title">要素信息</h3>
                        <div class="feature-extr__tags">
                            <dg-scrollbar>
                                <tag-info
                                    v-for="(item, idx) in tags"
                                    :key="idx"
                                    v-model="item.tags"
                                    :valueKey="item.value"
                                    :label="item.label"
                                    label-suffix="："
                                    label-width="100px"
                                />
                            </dg-scrollbar>
                        </div>
                        <div style="margin-left: 100px; padding-bottom: 10px">
                            <el-button type="primary" :disabled="$lodash.isEmpty(checkedTagMap)" @click="isSfz">
                                归属同一人员要素
                            </el-button>
                            <el-button @click="resetTags">重置</el-button>
                        </div>
                    </div>
                </div>
            </div>
            <!-- 右侧人员卡片 -->
            <div class="feature-extr__input">
                <div style="padding-right: 11px">
                    <div class="feature-extr__input-header">
                        <el-button type="primary" @click="addRyCard()">添加人员卡片</el-button>
                        <el-button @click="handleExpand">
                            <template v-if="!isCardOpen"> 展开 <i class="el-icon-arrow-down"></i></template>
                            <template v-else> 收起 <i class="el-icon-arrow-up"></i></template>
                        </el-button>
                    </div>
                    <div class="feature-extr__input-content">
                        <dg-scrollbar>
                            <div v-for="(card_item, card_idx) in cards" :key="card_idx">
                                <current-ipt
                                    v-model="card_item.data"
                                    :yslxMap="tagTypeMap"
                                    :sfzList="sfzList"
                                    @delCard="handleDelCard"
                                />
                            </div>
                        </dg-scrollbar>
                    </div>
                </div>
            </div>
        </div>
        <div v-footer>
            <el-button @click="cancle">取消</el-button>
            <el-button type="primary" :disabled="!ysListData.length" @click="saveYsList">确定</el-button>
        </div>
    </div>
</template>
<script>
import TextareaCopy from "@/components/textarea-copy";
import TagInfo from "./components/tag-info";
import CurrentIpt from "./components/current-ipt";

import { mapState } from "vuex";
import { factorTypes, getfactor } from "@/api/common";
import { handleFeatureHighLight, handleYsList, handleCardItem, handleCheckTags, cardItemBase } from "./data-process";

// import operateApi from '@/api/xsgl/xsgl_gdzs/operateApi'

export default {
    name: "feature-extr",
    components: {
        TextareaCopy,
        TagInfo,
        CurrentIpt
    },
    props: {
        xsxq: {
            type: String,
            default: ""
        },
        sfzList: {
            type: Array
        }
    },
    data() {
        return {
            test: {},
            tags: [], // 要素信息数组
            checkedTagMap: {}, // 选中的要素标签对象
            oldTags: [],
            cards: [],
            isCardOpen: true,
            tagTypeMap: {}, // 要素类型map
            // 自动可识别的为身份证号、车牌号、手机号码、QQ、固定电话（QQ和固定号码可能识别重复）、银行账号
            SFZ_EMPTY_INFO: "是否没有对应的身份证号"
        };
    },
    computed: {
        ysContentInfo() {
            // 根据要素信息高亮显示的内容
            let content = "";

            // 根据线索详情以及提取的要素信息进行内容展示的构造
            if (!_.isEmpty(this.tags)) {
                content = handleFeatureHighLight(this.tags, this.checkedTagMap, this.xsxq);
            }

            return content;
        },
        ysListData() {
            // 格式化后的要素列表数据
            let result = [];
            let ys_item = JSON.parse(JSON.stringify(cardItemBase)); // 要素列表单行的数据格式

            if (!_.isEmpty(this.cards)) {
                result = handleYsList(this.cards, ys_item);
            }
            return result;
        },
        ...mapState({
            defaultTagValue: (state) => ["500000", "100000", "200000", "400000", "300000"],
            constant: (state) => state.constant
        })
    },
    mounted() {
        // 查询要素提取内容
        // 查询要素类型表码数据
        this.getTagBmInfo();
    },
    methods: {
        // 是否有身份证判断
        isSfz() {
            if (!_.isEmpty(this.checkedTagMap) && _.isEmpty(this.checkedTagMap[this.constant.SFZH_DM])) {
                this.$dgConfirm(`是否没有对应的身份证号?`, "提示", {
                    confirmButtonText: "是",
                    cancelButtonText: "否",
                    type: "warning"
                }).then(() => {
                    this.addRyCard("merge"); // 新增
                });
            } else {
                this.addRyCard("merge"); // 新增
            }
        },
        // 新增/归属卡片(新增的卡片在最上面)
        addRyCard(add_type) {
            let card_empty_map = JSON.parse(JSON.stringify(cardItemBase)); // 右侧卡片空字段
            let checked_map = !_.isEmpty(this.checkedTagMap) ? JSON.parse(JSON.stringify(this.checkedTagMap)) : {}; // 当前选择的要素map

            // 如果有选中的要素信息，则生成包含要素信息的卡片，否则生成空卡片
            if (add_type == "merge") {
                // 当前选中的身份证号在右侧卡片列表中的位置
                let index_in_cards =
                    !_.isEmpty(this.cards) && !_.isEmpty(checked_map[this.constant.SFZH_DM])
                        ? _.findIndex(this.cards, (item) => item["data"].sfz == checked_map[this.constant.SFZH_DM])
                        : -1;
                let card_data = {}; // 最终的卡片要素信息
                // 如果身份证号在右侧卡片存在，则替换相应的字段内容
                if (index_in_cards != -1) {
                    // 当前身份证所在卡片上旧的要素信息
                    let old_card_data = Object.assign({}, this.cards[index_in_cards]["data"]);
                    // 根据左侧选中信息构造右侧数据
                    card_data = handleCardItem(this.checkedTagMap, old_card_data, this.tagTypeMap);
                    // 当前要素信息赋值
                    this.$set(this.cards[index_in_cards], "data", card_data);
                } else {
                    card_data = handleCardItem(this.checkedTagMap, cardItemBase, this.tagTypeMap);
                    // 添加新的卡片
                    this.cards.unshift({
                        data: card_data
                    });
                }
            } else {
                // 生成空卡片
                this.cards.unshift({
                    data: {
                        ...card_empty_map,
                        isOpenCard: true
                    }
                });
            }
        },
        // 关联要素信息 tag
        getValue(val) {
            // val = {value: '700000', label: '姓名', oldVal: '200000', text:'张三'}
            let index = this.tags.findIndex((v) => v.value === val.value);
            let newItem = [];
            if (index == -1) {
                this.tags.unshift({
                    value: val.value,
                    label: val.label,
                    tags: {
                        data: [val.text],
                        checked: []
                    }
                });
            } else {
                // 将鼠标选中的内容添加到所选类型的要素标签池中
                if (!this.tags[index].tags["data"]) this.tags[index].tags["data"] = [];
                newItem = [...this.tags[index].tags["data"], val.text];
                this.$set(this.tags[index]["tags"], "data", newItem);
            }

            // 如果之前有类型，移除旧要素类型下的标签
            if (val.oldVal) {
                let old_index = this.tags.findIndex((v) => v.value === val.oldVal);
                if (old_index != -1) {
                    this.tags[old_index]["tags"]["data"].splice(old_index, 1);
                }
            }
        },
        // 全部展开/ 或收起
        handleExpand() {
            this.isCardOpen = !this.isCardOpen;
        },
        // 删除卡片
        handleDelCard(card_data) {
            let index_in_card = _.findIndex(
                this.cards,
                (item) => JSON.stringify(item["data"]) == JSON.stringify(card_data)
            );

            if (index_in_card != -1) {
                this.cards.splice(index_in_card, 1);
            }
        },
        // 保存新增的要素信息
        saveYsList() {
            // 处理数据，将卡片中的要素信息提出来组成新的数组，简化数组层次
            let ystableList = [];
            this.cards &&
                this.cards.forEach((e) => {
                    if (!_.isEmpty(e)) {
                        ystableList.unshift(e.data);
                    }
                });
            // 拼接要素列表的数据结构
            let ys_list = JSON.parse(JSON.stringify(ystableList));
            if (!_.isEmpty(ys_list)) {
                ys_list = ys_list.map((item) => {
                    // 过滤掉空的要素类别
                    if (!_.isEmpty(item["ysList"])) {
                        item["ysList"] = item["ysList"].filter((ys) => ys["yslx"] && ys["ysnr"]);
                    }

                    return item;
                });
            }
            this.$emit("success", ys_list);
            this.$emit("close");
        },
        cancle() {
            this.$emit("close");
        },
        // 构造要素信息map
        getTagBmInfo() {
            factorTypes().then(({ data }) => {
                const obj = {};
                data.forEach((item) => {
                    obj[item.value] = item.label;
                });
                this.tagTypeMap = obj;
            });
        },
        // 重置要素信息
        resetTags() {
            let tags = !_.isEmpty(this.oldTags) ? JSON.parse(JSON.stringify(this.oldTags)) : [];
            this.$set(this, "tags", tags);
        },
        // 接口查询要素提取信息
        getYsInfo(tag_list) {
            getfactor({ var: this.xsxq }).then(({ data }) => {
                // 初始化要素信息展示数据
                if (!_.isEmpty(data)) {
                    tag_list.forEach((tag) => {
                        tag["tags"] = {
                            data: data[tag["value"]]||[],
                            checked: []
                        };
                    });
                }
                this.$set(this, "tags", tag_list);
                this.$set(this, "oldTags", JSON.parse(JSON.stringify(tag_list)));
            });
        }
    },
    watch: {
        tags: {
            deep: true,
            handler(new_val) {
                // 构造选中的要素标签对象checkedTagMap
                let checked_map = handleCheckTags(new_val);
                this.$set(this, "checkedTagMap", checked_map);
            }
        },
        // 监听要素信息map
        tagTypeMap: {
            deep: true,
            handler(new_val) {
                let tag_list = [];

                // 构造要素信息标签数据格式
                if (!_.isEmpty(new_val) && !_.isEmpty(this.defaultTagValue)) {
                    this.defaultTagValue.forEach((item) => {
                        if (new_val[item]) {
                            // 初始化要素信息
                            let tag_item = {
                                label: new_val[item],
                                value: item, // 要素类型
                                tags: {}
                            };
                            tag_list.push(tag_item);
                        }
                    });
                }

                // 接口查询提取的要素信息进行要素信息标签赋值
                if (!_.isEmpty(tag_list)) {
                    this.getYsInfo(tag_list);
                }
            }
        },
        // 监听展开合并按钮
        isCardOpen(new_val) {
            // 统一设置卡片的展开合并状态
            if (_.isEmpty(this.cards)) {
                return;
            }

            let cards_data = Object.assign([], this.cards);
            cards_data = cards_data.map((item) => {
                item["data"]["isOpenCard"] = new_val;
                return item;
            });
            this.$set(this, "cards", cards_data);
        }
    }
};
</script>
<style lang="scss" scoped>
.feature-extr {
    &__wrap {
        display: flex;
    }

    &__current {
        width: 55%;
    }

    &__current-info {
        padding-right: 40px;
    }

    &__tags {
        height: 276px;
    }

    &__input {
        flex: 1;
        padding-left: 20px;

        &-header {
            margin-top: 56px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
    }

    &__input-content {
        margin-top: 10px;
        height: 615px;
    }

    /deep/ .ysxx-alert {
        display: flex;
        align-items: center;
        width: calc(100% - 74px);
        margin-left: 10px;
    }
}

/deep/ .main-title {
    font-family: MicrosoftYaHei;
    display: flex;
    align-items: center;
    height: 56px;
    font-weight: bold;
    font-size: 16px;
    color: rgba(0, 0, 0, 0.85);
}
</style>
